package com.androdro.bluenote.coolstruttin1588;
/**
 * Cool Struttin'
 * Lover.java
 *
 * @author Hiroaki Sakuma <sakuma@androdro.com>
 * @version $Id$
 *
 * Copyright (C) androdro lab. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of the nor the names of its contributors may be used to
 *   endorse or promote products derived from this software without specific
 *   prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *
 */

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.Runnable;
import java.lang.Thread.UncaughtExceptionHandler;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;
import android.net.http.AndroidHttpClient;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

public class Lover
	implements
		Runnable,
		CoolStruttin1588 {

	/**
   *
   */

	private CoolStruttin root;
	private static Lover me;

	private Context c;
	private Resources r;
	private DisplayMetrics metrics;
	private static JSONObject jsonObj;
	private Handler h;
	private Thread t;
	private static Object lock;


	private Lover() {}

	private Lover(CoolStruttin root) {

		this.root = root;
		lock = new Object();

		try {

			this.c = this.root.getApplicationContext();
			this.r = this.c.getResources();

			this.metrics = this.root.getDisplayMetrics();
			this.h = new Handler();

		} catch (Exception e) {
			Toast.makeText(this.c, e.toString() + "on " + getClass().toString() + " " + e.getStackTrace()[0].getMethodName(), Toast.LENGTH_LONG).show();
		}

	}


	public static Lover getInstance(CoolStruttin root) {
		if (me == null) {
			me = new Lover(root);
		}
		return me;
	}


	public void start() {
		this.t = new Thread(this);
		this.t.start();
	}


	public void stop() {
		this.jsonObj = null;
	}


	public void run() {

		SippinAtBells.DecryptAES decryptor = SippinAtBells.getInstance().getFactory().getDecryptor();
		AndroidHttpClient client = null;
		byte[] jsonenc;
		String json = null;
		long time;

		try {

			while(json == null && ! this.root.isFinishing()) {

				synchronized(lock) {

					time = System.currentTimeMillis();

					Uri.Builder builder = new Uri.Builder();
					builder.scheme("http");
					builder.encodedAuthority(URL_API_CONFIG_HOST);
					builder.path(URL_API_CONFIG_PATH + ".b64");
					builder.appendQueryParameter("MANUFACTURER",    Build.MANUFACTURER);
					builder.appendQueryParameter("MODEL",           Build.MODEL);
					builder.appendQueryParameter("BRAND",           Build.BRAND);
					builder.appendQueryParameter("DEVICE",          Build.DEVICE);
					builder.appendQueryParameter("PRODUCT",         Build.PRODUCT);
					builder.appendQueryParameter("VERSION.RELEASE", Build.VERSION.RELEASE);
					builder.appendQueryParameter("VERSION.SDK",     Build.VERSION.SDK);
					builder.appendQueryParameter("VERSION.RELEASE", Build.VERSION.RELEASE);
					builder.appendQueryParameter("DISPLAY.WIDTH",   Integer.toString(metrics.widthPixels));
					builder.appendQueryParameter("DISPLAY.HEIGHT",  Integer.toString(metrics.heightPixels));

					HttpGet request = new HttpGet(builder.build().toString());
					request.addHeader("Referer", URL_HTTP_DEFAULT_REFERER);

					if (client == null) {
						client = AndroidHttpClient.newInstance(HTTP_USER_AGENT, this.c);
					}

					try {

						jsonenc = client.execute(request, new ResponseHandler<byte[]>() {
							@Override
							public byte[] handleResponse(HttpResponse response)
								throws
									ClientProtocolException,
									IOException {
										switch(response.getStatusLine().getStatusCode()) {
											case HttpStatus.SC_OK:
												return EntityUtils.toByteArray(response.getEntity());
											case HttpStatus.SC_NOT_FOUND:
												throw new RuntimeException(EntityUtils.toString(response.getEntity(), "UTF-8"));
											default:
												throw new RuntimeException(EntityUtils.toString(response.getEntity(), "UTF-8"));
										}
							}
						});

						json = decryptor.decrypt(Base64.decode(jsonenc, Base64.DEFAULT), "TestSecretKey");
//System.out.println(json);
						OutputStream out = this.c.openFileOutput("config.json.b64", this.c.MODE_WORLD_READABLE);
						out.write(jsonenc);
						out.close();

						this.jsonObj = new JSONObject(json);

					} catch(UnknownHostException uhe) {
						uhe.printStackTrace();
						final String error = uhe.toString();
						h.post(
							new Runnable() {
								public void run() {
									root.showError(error);
								}
							}
						);
						throw uhe;
					} finally {
						client.getConnectionManager().shutdown();
						client.close();
					}

					lock.notify();

				} //synchronized

				Thread.sleep(1000);

			}

		} catch (Exception e) {
			e.printStackTrace();
		}


	}


	public JSONObject getConfig() {

		while(this.jsonObj == null) {
			if (this.t == null) {
				this.t = new Thread(this);
				this.t.start();
			}
			try {
				Thread.sleep(50);
			} catch(InterruptedException ie) {
				ie.printStackTrace();
			}
		}

		return this.jsonObj;

	}


	public HashMap<String, Object> getHighways() {

		HashMap<String, Object> r = new HashMap<String, Object>();

		try {
			Iterator i = getConfig().getJSONObject("Body").getJSONObject("Highways").keys();
			while(i.hasNext()) {
				String k = i.next().toString();
				r.put(k, getConfig().getJSONObject("Body").getJSONObject("Highways").getJSONObject(k));
			}

		} catch (JSONException jsone) {
			jsone.printStackTrace();
		}

		return r;

	}


	public HashMap<String, Object> getHighwayName(String name) {

		HashMap<String, Object> r = new HashMap<String, Object>();

		try {
			r.put(name, getConfig().getJSONObject("Body").getJSONObject("Highways").getJSONObject(name).getString("Name"));
		} catch (JSONException jsone) {
			jsone.printStackTrace();
		}

		return r;

	}


	public String getHighwayImageURL(String name) {

		String r = new String();

		try {
			r = getConfig().getJSONObject("Body").getJSONObject("Highways").getJSONObject(name).getString("ImageURL");
		} catch (JSONException jsone) {
			jsone.printStackTrace();
		}

		return r;

	}


	public class LoverUncaughtExceptionHandler
		implements
			UncaughtExceptionHandler {


		public void uncaughtException(Thread t, Throwable throwable) {
			throwable.printStackTrace();
			root.showError(throwable.toString());
		}


	}


}
